/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.common.base.util;

import com.alibaba.fastjson2.*;
import com.je.common.base.DynaBean;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: je-platform
 * @author: LIULJ
 * @create: 2020/2/21
 * @description:
 */
public class JsonUtil {

    static {
        JSONFactory.setDefaultArraySupplier(() -> new ArrayList());
        JSONReader.Context context = JSONFactory.createReadContext(JSONReader.Feature.AllowUnQuotedFieldNames);
        JSON.config(JSONReader.Feature.AllowUnQuotedFieldNames);
        JSON.config(JSONWriter.Feature.PrettyFormat);
    }

    public static String[] jsonSqlToIdsStr(DynaBean dynaBean, String strData) {
        String tableCode = dynaBean.getStr("$TABLE_CODE$");
        String pkName = dynaBean.getStr("$PK_CODE$");
        if (StringUtil.isNotEmpty(strData) && StringUtil.isNotEmpty(tableCode)) {
            List<Map> sqlMapList = fromJsonArray(strData);
            String[] idsAarray = new String[sqlMapList.size()];
            for (int i = 0; i < sqlMapList.size(); ++i) {
                Map sqlMap = (Map) sqlMapList.get(i);
                idsAarray[i] = StringUtil.getDefaultValue(sqlMap.get(pkName), "");
            }
            return idsAarray;
        } else {
            return new String[0];
        }
    }

    public static List<Map> fromJsonArray(String json) {
        json = cleanJson(json);
        List<Map> dataList = fromJson(json, ArrayList.class);
        return dataList;
    }

    private static String cleanJson(String json) {
        return StringUtil.isNotEmpty(json) ? json.replaceAll("\n", "").trim() : "";
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        json = cleanJson(json);
        try {
            return JSON.parseObject(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            throw new PlatformException("字符串信息转换成实体对象报错", PlatformExceptionEnum.JE_CORE_JSONSTR_ERROR, new Object[]{json, clazz}, e);
        }
    }


    public static String convertNullStringsToNullObjects(String json) {
        JSONArray jsonArray = JSONArray.parseArray(json);
        for (int i = 0; i < jsonArray.size(); i++) {
            Object object = jsonArray.get(i);
            JSONObject jsonObject = JSONObject.parseObject(object.toString());
            // 遍历每个属性，将值为"null"的字符串转换为null对象
            for (String key : jsonObject.keySet()) {
                if (jsonObject.get(key).equals("null")) {
                    jsonObject.put(key, null);
                }
            }
        }
        return jsonArray.toString();
    }

}
